package com.scrx.ymg.action;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scrx.ymg.entity.Address;
import com.scrx.ymg.entity.HeadWithdarw;
import com.scrx.ymg.entity.OrderForm;
import com.scrx.ymg.entity.OrderFormDetails;
import com.scrx.ymg.entity.SeckillProduct;
import com.scrx.ymg.entity.SuperMarketInfo;
import com.scrx.ymg.entity.User;
import com.scrx.ymg.entity.UtilString;
import com.scrx.ymg.entity.goods_detail;
import com.scrx.ymg.service.address.IAddressService;
import com.scrx.ymg.service.head.IHeadService;
import com.scrx.ymg.service.orderform.IOrderFormService;
import com.scrx.ymg.service.seckill.ISeckillService;
import com.scrx.ymg.service.supermarket.ISuperMarketService;
import com.scrx.ymg.service.user.IUserService;
import com.scrx.ymg.util.HttpUtil;
import com.scrx.ymg.util.PayCommonUtil;
import com.scrx.ymg.util.PayConfigUtil;
import com.scrx.ymg.util.XMLUtil;
import com.swetake.util.Qrcode;

@Controller
@RequestMapping("/weChatPayAction")
public class WeChatPayAction {
	@Autowired
	private IHeadService heads;
	@Autowired
	private ISeckillService kills;

	@Autowired
	private IUserService users;

	@Autowired
	private IOrderFormService orders;

	@Autowired
	private IAddressService adds;

	@Autowired
	private ISuperMarketService sms;

	/**
	 * 申请广告发布,生成二维码扫码支付
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/advertisingWeChatPay", produces = "text/json;charset=UTF-8")
	public void advertisingWeChatPay(SeckillProduct product, HttpServletResponse response) {
		Logger logger = Logger.getLogger(WeChatPayAction.class);
		logger.info(product.getId() + "号广告:申请发布");
		try {
			// 1. 通过统一下单接口传入正确的参数(当然要包括我们的回调URL)与签名验证，从返回数据中得到code_url的对应数据
			String code_url = weixin_pay(product);
			// 2. 根据code_url的数据我们自己生成一个二维码图片，显示在浏览器网页上
			encoderQRCoder(code_url, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 团购小程序微信支付
	 * 
	 * @param product
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/WeChatPay", produces = "text/json;charset=UTF-8")
	public String WeChatPay(int seckillID, int userID, int num, int typeId) {
		Logger logger = Logger.getLogger(WeChatPayAction.class);
		logger.info("支付秒团商品id:" + seckillID);
		String code_url = "";
		// String msg=kills.createSeckillOrderForm(seckillID,userID,num,typeId);
		try {
			// 1. 通过统一下单接口传入正确的参数(当然要包括我们的回调URL)与签名验证，从返回数据中得到code_url的对应数据
			code_url = weixinPaySeckill(seckillID, userID, num, typeId);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return code_url;
	}

	/**
	 * 订单编号生成规则
	 * 
	 * @param userID
	 * @param superID
	 * @return
	 */
	public String orderIDGenerativeRuleT(int userID, int agentId) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmss");
		String date = formatter.format(new Date());
		String orderid = "t" + agentId + date + userID;
		return orderid;
	}

	/**
	 * 团购微信支付
	 * 
	 * @param product
	 * @return
	 * @throws Exception
	 */
	public String weixinPaySeckill(int seckillID, int userID, int num, int typeId) {
		String urlCode = "false";
		try {
			SeckillProduct seckill = kills.getSeckillOne(seckillID);
			User user = users.findById(userID);
			Gson gson = new Gson();
			Double price = seckill.getSeckillPrice() * 100 * num;
			// 账号信息
			String appid = PayConfigUtil.APPID; // appid
			// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
			String mch_id = PayConfigUtil.MCH_ID; // 商业号
			String key = PayConfigUtil.API_KEY; // key
			String spbill_create_ip = PayConfigUtil.CREATE_IP; // 获取发起电脑 ip
			String notify_url = PayConfigUtil.JSAPI_URL; // 回调接口
			String out_trade_no = orderIDGenerativeRuleT(userID, seckill.getAgentId()); // 订单号
			String body = "乙秒购商城团购-" + seckill.getProductName(); // 商品名称
			String total_fee = Integer.toString(price.intValue()); // 订单总金额
																	// 注意：价格的单位是分
			String trade_type = "JSAPI";
			String openid = user.getUserId();

			String currTime = PayCommonUtil.getCurrTime();
			String strTime = currTime.substring(8, currTime.length());
			String strRandom = PayCommonUtil.buildRandom(4) + "";
			String nonce_str = strTime + strRandom; // 随机字符串

			// goods_detail goods= new goods_detail();
			// goods.setGoods_id(seckill.getId().toString());
			// goods.setGoods_name(seckill.getProductName());
			// goods.setQuantity(num);
			// goods.setPrice(price.intValue());
			// goods.setUserId(Integer.toString(userID));
			//
			// String detail=gson.toJson(goods);
			// String attach=gson.toJson(goods);

			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			packageParams.put("appid", appid);
			packageParams.put("mch_id", mch_id);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", body);
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("total_fee", total_fee);
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", notify_url);
			packageParams.put("trade_type", trade_type);
			packageParams.put("openid", openid);
			// packageParams.put("detail", detail);
			// packageParams.put("attach", attach);

			String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);// 签名
			packageParams.put("sign", sign);

			String requestXML = PayCommonUtil.getRequestXml(packageParams);

			String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);

			Map map = XMLUtil.doXMLParse(resXml);
			String msg = "false";
			if ("SUCCESS".equals(map.get("result_code"))) {
				msg = kills.createSeckillOrderForm(out_trade_no, seckillID, userID, num, typeId);
			}

			if (msg == "true") {
				String prepay_id = (String) map.get("prepay_id");

				String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
				String stringSignTemp = "appId=" + appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id
						+ "&signType=MD5&timeStamp=" + timeStamp;
				String paySign = PayCommonUtil.sign(stringSignTemp, "&key=" + key, "utf-8").toUpperCase();

				UtilString util = new UtilString();
				util.setTimeStamp(timeStamp);
				util.setSignType("MD5");
				util.setNonceStr(nonce_str);
				util.setPackages("prepay_id=" + prepay_id);
				util.setPaySign(paySign);
				urlCode = gson.toJson(util);
			}

			// String return_code = (String) map.get("return_code");
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return urlCode;
	}

	/**
	 * 团购微信支付回调函数
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/callBackSeckillPay", produces = "text/json;charset=UTF-8")
	public void callBackSeckillPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Logger logger = Logger.getLogger(WeChatPayAction.class);
		logger.info("回调成功");
		// 读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		// 解析xml成map
		Map<String, String> m = new HashMap<String, String>();
		m = XMLUtil.doXMLParse(sb.toString());

		// 过滤空 设置 TreeMap
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);

			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}

		// 账号信息
		String key = PayConfigUtil.API_KEY; // key

		logger.info(packageParams);
		String resXml = "";
		// 判断签名是否正确
		if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {
			// ------------------------------
			// 处理业务开始
			// ------------------------------

			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				// 这里是支付成功
				////////// 执行自己的业务逻辑////////////////
				String mch_id = (String) packageParams.get("mch_id");
				String openid = (String) packageParams.get("openid");
				String is_subscribe = (String) packageParams.get("is_subscribe");
				// 商户订单号
				String out_trade_no = (String) packageParams.get("out_trade_no");
				// 订单金额
				String total_fee = (String) packageParams.get("total_fee");
				String attach = (String) packageParams.get("attach");
				Gson gson = new Gson();
				goods_detail res = gson.fromJson(attach, goods_detail.class);
				OrderForm order = orders.getOrderFormByOrderId(out_trade_no);
				String msg = "false";
				if (order != null && order.getStatus() == -1) {
					order.setStatus(2);
					msg = orders.updateOrderFormAndHeadMoney(order);
				}
				////////// 执行自己的业务逻辑////////////////
				// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
				if (msg.equals("true")) {
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				} else {
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[生成订单失败]]></return_msg>" + "</xml> ";
				}
			} else {
				logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			}

		} else {
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[签名验证失败]]></return_msg>" + "</xml> ";
			logger.info("通知签名验证失败");
		}
		// ------------------------------
		// 处理业务完毕
		// ------------------------------
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(resXml.getBytes());
		out.flush();
		out.close();
		logger.info("回调完成");

	}

	/**
	 * 生成二维码QRCode图片
	 * 
	 * @param content
	 * @param response
	 */
	public void encoderQRCoder(String content, HttpServletResponse response) {
		try {
			Qrcode handler = new Qrcode();
			handler.setQrcodeErrorCorrect('M');
			handler.setQrcodeEncodeMode('B');
			handler.setQrcodeVersion(7);

			byte[] contentBytes = content.getBytes("UTF-8");

			BufferedImage bufImg = new BufferedImage(150, 150, BufferedImage.TYPE_INT_RGB);

			Graphics2D gs = bufImg.createGraphics();

			gs.setBackground(Color.WHITE);
			gs.clearRect(0, 0, 240, 240);

			// 设定图像颜色：BLACK
			gs.setColor(Color.BLACK);

			// 设置偏移量 不设置肯能导致解析出错
			int pixoff = 2;
			// 输出内容：二维码
			if (contentBytes.length > 0 && contentBytes.length < 124) {
				boolean[][] codeOut = handler.calQrcode(contentBytes);
				for (int i = 0; i < codeOut.length; i++) {
					for (int j = 0; j < codeOut.length; j++) {
						if (codeOut[j][i]) {
							gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
						}
					}
				}
			} else {
				System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");
			}

			gs.dispose();
			bufImg.flush();
			// 生成二维码QRCode图片
			ImageIO.write(bufImg, "jpg", response.getOutputStream());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 广告扫码支付生成支付路径
	 * 
	 * @param product
	 * @return
	 * @throws Exception
	 */
	public String weixin_pay(SeckillProduct product) {
		String urlCode = "";
		try {
			// 账号信息
			String appid = PayConfigUtil.APPID; // appid
			// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
			String mch_id = PayConfigUtil.MCH_ID; // 商业号
			String key = PayConfigUtil.API_KEY; // key

			String currTime = PayCommonUtil.getCurrTime();
			String strTime = currTime.substring(8, currTime.length());
			String strRandom = PayCommonUtil.buildRandom(4) + "";
			String nonce_str = strTime + strRandom;
			SeckillProduct seckill = kills.getSeckillOne(product.getId());
			seckill.setOrderNum(orderNumM(seckill.getOtherId()));
			kills.updateSeckillProduct(seckill);
			HeadWithdarw head = heads.selectHeadWithdarw();
			Double price = head.getAdRate() * 100;
			String order_price = Integer.toString(price.intValue()); // 价格
																		// 注意：价格的单位是分
			String body = seckill.getProductName(); // 商品名称
			String out_trade_no = seckill.getOrderNum(); // 订单号

			// 获取发起电脑 ip
			String spbill_create_ip = PayConfigUtil.CREATE_IP;
			// 回调接口
			String notify_url = PayConfigUtil.NOTIFY_URL;
			String trade_type = "NATIVE";

			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			packageParams.put("appid", appid);
			packageParams.put("mch_id", mch_id);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", body);
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("total_fee", order_price);
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", notify_url);
			packageParams.put("trade_type", trade_type);

			String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);
			packageParams.put("sign", sign);

			String requestXML = PayCommonUtil.getRequestXml(packageParams);

			String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);

			Map map = XMLUtil.doXMLParse(resXml);

			// String return_code = (String) map.get("return_code");
			// String prepay_id = (String) map.get("prepay_id");
			urlCode = (String) map.get("code_url");

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return urlCode;
	}

	/**
	 * 广告扫码支付回调 在回调的URL中添加我们自己业务逻辑处理。
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/weixin_notify", produces = "text/json;charset=UTF-8")
	public void weixin_notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Logger logger = Logger.getLogger(WeChatPayAction.class);
		logger.info("回调成功");
		// 读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		// 解析xml成map
		Map<String, String> m = new HashMap<String, String>();
		m = XMLUtil.doXMLParse(sb.toString());

		// 过滤空 设置 TreeMap
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);

			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}

		// 账号信息
		String key = PayConfigUtil.API_KEY; // key

		logger.info(packageParams);
		String resXml = "";
		// 判断签名是否正确
		if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {
			// ------------------------------
			// 处理业务开始
			// ------------------------------
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				// 这里是支付成功
				////////// 执行自己的业务逻辑////////////////
				String mch_id = (String) packageParams.get("mch_id");
				String openid = (String) packageParams.get("openid");
				String is_subscribe = (String) packageParams.get("is_subscribe");
				// 商户订单号
				String out_trade_no = (String) packageParams.get("out_trade_no");
				// 订单金额
				String total_fee = (String) packageParams.get("total_fee");
				String attach = (String) packageParams.get("attach");
				String msg = kills.applyCheckSeckillProduct(out_trade_no);

				// logger.info("mch_id:"+mch_id);
				// logger.info("openid:"+openid);
				// logger.info("is_subscribe:"+is_subscribe);
				// logger.info("out_trade_no:"+out_trade_no);
				// logger.info("total_fee:"+total_fee);

				////////// 执行自己的业务逻辑////////////////

				// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
				if (msg.equals("true")) {
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				} else {
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[服务器申请广告失败]]></return_msg>" + "</xml> ";
				}

			} else {
				logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			}

		} else {
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[签名验证失败]]></return_msg>" + "</xml> ";
			logger.info("通知签名验证失败");
		}
		// ------------------------------
		// 处理业务完毕
		// ------------------------------
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(resXml.getBytes());
		out.flush();
		out.close();
		logger.info("回调完成");

	}

	/**
	 * 超市微信支付
	 * 
	 * @param product
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/weixinPaySuper", produces = "text/json;charset=UTF-8")
	public String weixinPaySuper(String detailsjson, int userID, int paymentType, double shipping_fee, int superId,
			Double totalMoney, String addressID) {
		Gson gson = new Gson();
		String urlCode = "";
		try {
			User user = users.findById(userID);
			// SeckillProduct seckill =kills.getSeckillOne(seckillID);
			Address add = adds.getAddressByID(addressID);
			SuperMarketInfo superinfo = sms.findByID(superId);
			List<OrderFormDetails> details = gson.fromJson(detailsjson, new TypeToken<List<OrderFormDetails>>() {
			}.getType());
			String orderId = orders.createOrderFormWX(user, superinfo, add, shipping_fee, totalMoney, paymentType,
					details, -1);
			if (orderId.equals("251")) {// 库存不足
				return "251";
			}
			Double price = totalMoney * 100;
			// 账号信息
			String appid = PayConfigUtil.APPID; // appid
			// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
			String mch_id = PayConfigUtil.MCH_ID; // 商业号
			String key = PayConfigUtil.API_KEY; // key
			String spbill_create_ip = PayConfigUtil.CREATE_IP; // 获取发起电脑 ip
			String notify_url = PayConfigUtil.CS_URL; // 回调接口
			String out_trade_no = orderId; // 订单号
			String body = "乙秒购商城-超市购物"; // 商品名称
			String total_fee = Integer.toString(price.intValue()); // 订单总金额
																	// 注意：价格的单位是分
			String trade_type = "JSAPI";
			String openid = user.getUserId();

			String currTime = PayCommonUtil.getCurrTime();
			String strTime = currTime.substring(8, currTime.length());
			String strRandom = PayCommonUtil.buildRandom(4) + "";
			String nonce_str = strTime + strRandom; // 随机字符串

			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			packageParams.put("appid", appid);
			packageParams.put("mch_id", mch_id);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", body);
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("total_fee", total_fee);
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", notify_url);
			packageParams.put("trade_type", trade_type);
			packageParams.put("openid", openid);

			String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);// 签名
			packageParams.put("sign", sign);

			String requestXML = PayCommonUtil.getRequestXml(packageParams);

			String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);

			Map map = XMLUtil.doXMLParse(resXml);
			String prepay_id = (String) map.get("prepay_id");

			String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
			String stringSignTemp = "appId=" + appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id
					+ "&signType=MD5&timeStamp=" + timeStamp;
			String paySign = PayCommonUtil.sign(stringSignTemp, "&key=" + key, "utf-8").toUpperCase();

			UtilString util = new UtilString();
			util.setTimeStamp(timeStamp);
			util.setSignType("MD5");
			util.setNonceStr(nonce_str);
			util.setPackages("prepay_id=" + prepay_id);
			util.setPaySign(paySign);
			urlCode = gson.toJson(util);
			// String return_code = (String) map.get("return_code");
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return urlCode;
	}

	/**
	 * 超市微信支付回调函数
	 * 
	 * @throws IOException
	 * @throws JDOMException
	 */
	@ResponseBody
	@RequestMapping(value = "/callBackSuperPay", produces = "text/json;charset=UTF-8")
	public void callBackSuperPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Logger logger = Logger.getLogger(WeChatPayAction.class);
		logger.info("回调成功");
		// 读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		// 解析xml成map
		Map<String, String> m = new HashMap<String, String>();
		m = XMLUtil.doXMLParse(sb.toString());

		// 过滤空 设置 TreeMap
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);

			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}

		// 账号信息
		String key = PayConfigUtil.API_KEY; // key

		logger.info(packageParams);
		String resXml = "";
		// 判断签名是否正确
		if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {
			// ------------------------------
			// 处理业务开始
			// ------------------------------

			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				// 这里是支付成功
				////////// 执行自己的业务逻辑////////////////
				String mch_id = (String) packageParams.get("mch_id");
				String openid = (String) packageParams.get("openid");
				String is_subscribe = (String) packageParams.get("is_subscribe");
				// 商户订单号
				String out_trade_no = (String) packageParams.get("out_trade_no");
				// 订单金额
				String total_fee = (String) packageParams.get("total_fee");
				Gson gson = new Gson();
				OrderForm order = orders.getOrderFormByOrderId(out_trade_no);
				String msg = "false";
				if (order.getStatus() == -1) {
					order.setStatus(1);
					msg = orders.updateOrderFormAndHeadMoney(order);
					// msg=orders.updateOrderForm(order);
				}
				////////// 执行自己的业务逻辑////////////////
				// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
				if (msg.equals("true")) {
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				} else {
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[重复回调函数]]></return_msg>" + "</xml> ";
				}
			} else {
				logger.info("支付失败,错误信息：" + packageParams.get("err_code"));
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			}

		} else {
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[签名验证失败]]></return_msg>" + "</xml> ";
			logger.info("通知签名验证失败");
		}
		// ------------------------------
		// 处理业务完毕
		// ------------------------------
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(resXml.getBytes());
		out.flush();
		out.close();
		logger.info("回调完成");

	}

	/**
	 * 订单编号生成规则
	 * 
	 * @param userID
	 * @param superID
	 * @return
	 */
	public String orderIDGenerativeRuleC(int userID, int superID) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmss");
		String date = formatter.format(new Date());
		String orderid = "c" + superID + date + userID;
		return orderid;
	}

	public String orderNumM(int otherId) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmss");
		String date = formatter.format(new Date());
		String orderid = "c" + otherId + date;
		return orderid;
	}

}
